package com.app.library.base

import android.app.Activity
import android.app.Dialog
import android.graphics.Point
import android.os.Bundle
import android.view.Display
import android.view.Gravity
import android.view.Window
import android.view.WindowManager
import com.app.library.R
import com.app.library.databinding.LayoutLoadingBinding
import com.app.library.ext.visible
import com.blankj.utilcode.util.NetworkUtils

class LoadingDialog(private val activity: Activity) : Dialog(activity, R.style.CustomDialog) {

    private var message: String = ""
    private var mScreenPoint: Point = Point()

    private lateinit var binding: LayoutLoadingBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = LayoutLoadingBinding.inflate(layoutInflater)
        setContentView(binding.root)
//        initDialogWindow(0.45f)
        if (message.isNullOrEmpty()){
            binding.tvMessage.visible(false)
        }else{
            binding.tvMessage.visible(true)
            binding.tvMessage.text = message
        }
    }

    private fun initDialogWindow(width: Float) {
        activity ?: return
        val dialogWindow: Window = window ?: return
        dialogWindow.setGravity(Gravity.CENTER)
        val m: WindowManager? = activity.windowManager
        val d: Display = m?.defaultDisplay ?: return // 获取屏幕宽、高用
        try {
            d.getSize(mScreenPoint)
        } catch (ignore: NoSuchMethodError) { // Older device
            mScreenPoint.x = d.width
            mScreenPoint.y = d.height
        }
        val p: WindowManager.LayoutParams = dialogWindow.attributes // 获取对话框当前的参数值
        p.width = (mScreenPoint.x * width).toInt()
        dialogWindow.setWindowAnimations(R.style.MpDialogCommonAnim)
        dialogWindow.attributes = p
    }

    /**
     * 显示dialog
     *
     * @return
     */
    fun show(msg: String?) {
        if (activity != null && !activity.isDestroyed && !activity.isFinishing && !isShowing) {
            try {
                message = msg ?: ""
                super.show()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    override fun show() {
        message = ""
        if (!hasNet()){//无网络不loading
            return
        }
        super.show()
    }
    fun hasNet(): Boolean {
        if (NetworkUtils.getNetworkType() == NetworkUtils.NetworkType.NETWORK_NO) {
            return false
        }
        return true
    }
    override fun dismiss() {
        if (activity != null && !activity.isDestroyed && !activity.isFinishing && isShowing) {
            try {
                super.dismiss()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    fun setMessage(msg: String?) {
        message = msg ?: ""
        if (this::binding.isInitialized && message != null) {
            binding.tvMessage.text = message
        }
    }

}